import Clipboard from 'clipboard'

function clipboardSuccess() {
  return new Promise((resolve) => {
    resolve('')
  })
}

function clipboardError() {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line prefer-promise-reject-errors
    reject()
  })
}

export default async function handleClipboard(text: string, event: any) {
  const clipboard: any = new Clipboard(event.target, {
    text: () => text
  })

  try {
    clipboard.on('success', async () => {
      await clipboardSuccess()
      clipboard.destroy()
    })

    clipboard.on('error', async () => {
      await clipboardError()
      clipboard.destroy()
    })

    clipboard.onClick(event)
    // 因为 `Clipboard.js` 不支持 Promise，此处返回一个空的 resolved Promise 仅为了链式调用 .then()
    return Promise.resolve()
  } catch (error) {
    return Promise.reject(error)
  }
}
